package com.saris.primego.web.controller.user;

import com.saris.primego.common.constant.JwtClaimsConstant;
import com.saris.primego.common.properties.JwtProperties;
import com.saris.primego.common.result.Result;
import com.saris.primego.common.utils.JwtUtil;
import com.saris.primego.pojo.dto.UserLoginDTO;
import com.saris.primego.pojo.entity.User;
import com.saris.primego.pojo.vo.UserLoginVO;
import com.saris.primego.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController("userUserController")
@RequestMapping("/user/user")
@Tag(name = "C端用户")
public class UserController {

    private final ModelMapper modelMapper;
    private final UserService userService;
    private final JwtProperties jwtProperties;

    public UserController(UserService userService, ModelMapper modelMapper, JwtProperties jwtProperties) {
        this.userService = userService;
        this.modelMapper = modelMapper;
        this.jwtProperties = jwtProperties;
    }

    @PostMapping("/login")
    @Operation(summary = "微信登录", method = "POST")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO dto) {
        //微信登录
        User user = userService.wxLogin(dto);

        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO vo = modelMapper.map(user, UserLoginVO.class);
        vo.setToken(token);
        return Result.success(vo);
    }

}
